package cn.js189.uqc.task;

import cn.hutool.extra.spring.SpringUtil;
import cn.js189.common.constants.Constants;
import cn.js189.common.constants.InvoiceConstant;
import cn.js189.common.constants.URLKeyContants;
import cn.js189.common.util.RSAUtils;
import cn.js189.common.util.helper.DateHelper;
import cn.js189.common.util.helper.UUIDHelper;
import cn.js189.uqc.domain.invoice.InnerApiLog;
import cn.js189.uqc.domain.NacosCommon;
import cn.js189.uqc.mapper.CheckInfoMapper;
import cn.js189.uqc.redis.RedisOperation;
import cn.js189.uqc.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayEbppInvoiceInfoSendRequest;
import com.alipay.api.response.AlipayEbppInvoiceInfoSendResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class QuartzPdfUrl {
	private static final String URL = "/gateway.do";
	private static final String FORMAT = "json";
	private static final String CHARSET = "UTF-8";
	private static final String SIGN_TYPE = "RSA2";
	private static final String SYNC_PDF = "SYNC_PDF_";

	@Resource
	private RedisOperation redisOperation;

	static final Logger logger = LoggerFactory.getLogger(QuartzPdfUrl.class);
	static final String PDFURL = URLPropertyUtil.getContextProperty(URLKeyContants.ALI_PDF_URL);

	@Resource
	private CheckInfoMapper checkInfoMapper;

    /**
     * 实时轮询
     */
	public void syncPdf() {
		logger.info("PDF同步任务开始运行...{}", new Date());
		List<Map<String, String>> list = checkInfoMapper.selectListUpdatePdf();
		if (list == null || list.isEmpty()) {
			logger.info("没有要同步的url数据");
			return;
		}
		forListSyncPdf(list);
	}
	
	public void forListSyncPdf(List<Map<String, String>> list){
		//更新状态和pdf
		for (Map<String, String> map : list) {
			logger.info("正在同步invoiceId={}", map.get("invoiceId"));

			String lockValue = UUIDHelper.getUUID();
			String lockKey = SYNC_PDF + map.get("invoiceId");
            String orderId = map.get("orderId");

			try {
				String lockResult = RedisUtil.tryLock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
				if (!StringUtils.equals(lockResult, RedisUtil.LOCK_SUCCESS)) {
					logger.info("PDF获取锁失败invoiceId:{}", map.get("invoiceId"));
					continue;
				}

				EInvoiceUtil.setHeadMap(map.get("areaCode"));
				String httpUrl = EInvoiceUtil.getJsRemoteUrl("invoiceJS", map.get("invoiceId"), map.get("areaCode"));
				logger.info("企信电子发票信息查询接口URL:{}", httpUrl);
				long t1 = System.currentTimeMillis();
				String res = HttpClientUtils.sendGet(httpUrl, EInvoiceUtil.getInvoiceHeadMap());
				long t2 = System.currentTimeMillis();

				logger.info("企信电子发票信息查询耗时"+(t2-t1)+"毫秒");

				if (StringUtils.isNotEmpty(res)) {
					parse(res, map);
				}else {
					logger.info("企信电子发票信息查询接口出参为空!");
                    // 超时处理
                    delayHandle(map, orderId,"1");
				}

				RedisUtil.unlock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
			} catch (Exception ex) {
				logger.info("invoiceId:{} PDF同步任务异常 {}：", map.get("invoiceId"), ex.getMessage());
				RedisUtil.unlock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
                // 超时处理
                delayHandle(map, orderId,"1");
			}
		}
	}
	
	public void parse(String res,Map<String, String> map){
		logger.info("企信电子发票信息查询接口出参:{}", res);
		//请求成功直接返回数据信息
		JSONObject resBody = JSON.parseObject(res);
		String invoiceId = resBody.getString("invoiceId");
		String url = resBody.getString("url");
		String invoiceDate = resBody.getString("invoiceDate");
		String invoiceCode = resBody.getString("invoiceCode");
		String invoiceNo = resBody.getString("invoiceNo");
		String fakeCode = resBody.getString("fakeCode");

		if (null == invoiceId || null == url || null == invoiceDate || null == invoiceCode || null == invoiceNo || null == fakeCode ||
				invoiceId.isEmpty() || url.isEmpty() || invoiceDate.isEmpty() || invoiceCode.isEmpty() || invoiceNo.isEmpty()) {
			logger.info("发票查询接口：企信回参必填字段为空!");
            // 超时处理
            delayHandle(map, map.get("orderId"),"1");
		} else {
            String dateResult = getDateResult(invoiceDate);
            invoiceDate = getResult(invoiceDate);
            if (dateResult.isEmpty() || invoiceDate.isEmpty()) {
                logger.info("invoiceId:{} 开票日期字段异常invoiceDateError",map.get("invoiceId"));
                return;
            }

            //url地址截取
            if (url.contains("pdfurl=")){
                url = url.substring(url.indexOf("pdfurl=") + 7);
            }
            logger.info("mysql开始更新发票信息");
            updateInvoice(map.get("invoiceId"), map.get("orderId"), url, invoiceDate, invoiceCode, invoiceNo, fakeCode);

            //等于phoneType为2才发短信
            logger.info("调用掌厅接口推送短信邮件");
            sendData(map, url);
            logger.info("掌厅接口调用完成,检测支付宝授权状态");
		}
	}
	

    /**
     * 超时轮询
     */
    public void syncDelayPdf() {
        logger.info("PDF同步任务开始运行...{}", new Date());
        List<Map<String, String>> list = checkInfoMapper.selectListUpdateDelayPdf();
        if (list == null || list.isEmpty()) {
            logger.info("没有要同步的url数据");
            return;
        }
        forList(list);
    }
    
    public void forList(List<Map<String, String>> list){
    	//更新状态和pdf
        for (Map<String, String> map : list) {
            logger.info("正在同步invoiceId={}", map.get("invoiceId"));

            String lockValue = UUIDHelper.getUUID();
            String lockKey = SYNC_PDF + map.get("invoiceId");
            String orderId = map.get("orderId");

            try {
                String lockResult = RedisUtil.tryLock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
                if (!StringUtils.equals(lockResult, RedisUtil.LOCK_SUCCESS)) {
                    logger.info("PDF获取锁失败invoiceId:{}", map.get("invoiceId"));
                    continue;
                }

                EInvoiceUtil.setHeadMap(map.get("areaCode"));
                String httpUrl = EInvoiceUtil.getJsRemoteUrl("invoiceJS", map.get("invoiceId"), map.get("areaCode"));
                logger.info("企信电子发票信息查询接口URL:{}", httpUrl);
                String res = HttpClientUtils.sendGet(httpUrl, EInvoiceUtil.getInvoiceHeadMap());

                if (StringUtils.isNotEmpty(res)) {
                	
                	parseResp(res, map, orderId);
                }else {
                    logger.info("企信电子发票信息查询接口出参为空!");
                    // 超时处理
                    delayHandle(map, orderId,"2");
                }

                RedisUtil.unlock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
            } catch (Exception ex) {
                logger.info("invoiceId:{} PDF同步任务异常 {}：", map.get("invoiceId"), ex.getMessage());
                RedisUtil.unlock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
                delayHandle(map, orderId,"2");
            }
        }
    }
    
    public void parseResp(String res,Map<String, String> map,String orderId){
        logger.info("企信电子发票信息查询接口出参:{}", res);
        //请求成功直接返回数据信息
        JSONObject resBody = JSON.parseObject(res);
        String qxInvoiceId = resBody.getString("invoiceId");
        String url = resBody.getString("url");
        String invoiceDate = resBody.getString("invoiceDate");
        String invoiceCode = resBody.getString("invoiceCode");
        String invoiceNo = resBody.getString("invoiceNo");
        String fakeCode = resBody.getString("fakeCode");

        if (null == qxInvoiceId || null == url || null == invoiceDate || null == invoiceCode || null == invoiceNo || null == fakeCode ||
                qxInvoiceId.isEmpty() || url.isEmpty() || invoiceDate.isEmpty() || invoiceCode.isEmpty() || invoiceNo.isEmpty()) {
            logger.info("发票查询接口：企信回参必填字段为空!");
            // 超时处理
            delayHandle(map, orderId,"2");
        } else {
            String dateResult = getDateResult(invoiceDate);
            invoiceDate = getResult(invoiceDate);

            if (dateResult.isEmpty() || invoiceDate.isEmpty()) {
                logger.info("invoiceId:{} 开票日期字段异常invoiceDateError",map.get("invoiceId"));
                return;
            }

            //url地址截取
            if (url.contains("pdfurl=")){
                url = url.substring(url.indexOf("pdfurl=") + 7);
            }
            logger.info("mysql开始更新发票信息");
            updateInvoice(map.get("invoiceId"), orderId, url, invoiceDate, invoiceCode, invoiceNo, fakeCode);

            //等于phoneType为2才发短信
            logger.info("调用掌厅接口推送短信邮件");
            sendData(map, url);
            logger.info("掌厅接口调用完成,检测支付宝授权状态");
        }
    
    }

    private void delayHandle(Map<String, String> map, String orderId ,String type) {
        Map<String,?> tempMap = map;
        Date createDate = (Date) tempMap.get("gmtCreate");
        Date currentDate = new Date();

        int rentDays = DateHelper.differentDaysByMillisecond(createDate, currentDate);
        int rentMinutes = DateHelper.differentMinutesByMillisecond(createDate, currentDate);
        if("1".equals(type) && rentMinutes >5 ){ // 开票时间超过5分钟
            String invoiceId = map.get("invoiceId");
            checkInfoMapper.updateDetailDelayFlag(invoiceId, orderId,"1");
            logger.info("获取发票Pdf信息invoiceId:{} 已超过5分钟！", invoiceId);
        }else if("2".equals(type) && rentDays >30){ // 开票时间超过30天
            String invoiceId = map.get("invoiceId");
            checkInfoMapper.updateDetailDelayFlag(invoiceId, orderId,"2");
            logger.info("获取发票Pdf信息invoiceId:{} 已超过30天！", invoiceId);
        }
    }


	private void updateInvoice(String invoiceId, String orderId, String url, String invoiceDate, String invoiceCode, String invoiceNo, String fakeCode) {
		int count = checkInfoMapper.updateDetailByInvoiceId(invoiceId, orderId, url, invoiceDate, invoiceCode, invoiceNo, fakeCode);
		logger.info("mysql发票Pdf信息更新invoiceId:{} 更新状态:{}", invoiceId, count > 0);

	}

	/**
	 * 同步支付宝电子发票插卡
	 */
	public void syncAliCard() {
		logger.info("开始同步支付宝侧插卡===");
		try {
			List<Map<String, String>> lm = checkInfoMapper.selectInfoByOrderId();
			logger.debug("同步支付宝侧插卡数据==={}", lm);
			if (null != lm && (!lm.isEmpty())) {
				for (int i = 0; i < lm.size(); i++) {
					Map<String, String> m = lm.get(i);
					syncAliCard2(m);
				}
			}
		} catch (Exception e) {
			logger.info("支付宝插卡异常:{}", e.getMessage());
		}
	}

	public void syncAliCard2(Map<String, String> m) throws AlipayApiException {
		logger.info("同步支付宝侧发票信息==={}", m);
		String invoiceId = m.get("invoiceId");
		String invoiceCode = m.get("invoiceCode");
		String invoiceDate = m.get("invoiceDate");
		String invoiceNo = m.get("invoiceNo");
		logger.debug("mysql发票Pdf信息更新成功invoiceId:{},检查支付宝授权状态", invoiceId);

		String lockValue = UUIDHelper.getUUID();
		String lockKey = SYNC_PDF + invoiceId;

		//检测支付宝是否授权
		if (null != m.get(Constants.OPEN_ID) && !m.get(Constants.OPEN_ID).isEmpty() && ("1").equals(m.get("aliAuth"))) {
			logger.info("支付宝已授权,准备推送发票");

			String lockResult = RedisUtil.tryLock(redisOperation, "电子发票支付宝插卡", lockKey, lockValue);
			if (!StringUtils.equals(lockResult, RedisUtil.LOCK_SUCCESS)) {
				logger.info("PDF获取锁失败invoiceId:{}", invoiceId);
				return;
			}

			//调用支付宝推送接口
			String money = String.valueOf(m.get("money"));
			if (money.indexOf('.') > -1) {
				money = money.replace(".0", "");
			}

			money = changeF2Y(Integer.parseInt(money));
			Map<String, String> item = new HashMap<>();
			item.put("user_id", m.get(Constants.OPEN_ID).trim());
			item.put("invoice_code", invoiceCode);
			item.put("invoice_no", invoiceNo);
			item.put("invoice_date", invoiceDate);
			item.put("sum_amount", money);
			item.put("ex_tax_amount", money);
			item.put("tax_amount", "0.00");
			item.put("item_name", (m.get(Constants.DESCRIPTION) == null || m.get(Constants.DESCRIPTION).isEmpty()) ? "*电信服务*电信服务费" : m.get(Constants.DESCRIPTION));
			item.put("item_no", "1010101990000000000");
			item.put("item_unit", "张");
			item.put("item_quantity", "1");
			item.put("item_unit_price", money);
			item.put("item_ex_tax_amount", money);
			item.put("item_tax_rate", "0.00");
			item.put("item_tax_amount", "0.00");
			item.put("item_sum_amount", money);
			item.put("row_type", "0");
			item.put("out_trade_no", getTradeNo());
			item.put("invoice_type", "BLUE");
			item.put("invoice_kind", "PLAIN");
			item.put("title_name", m.get("titleName"));
			item.put("payer_register_no", "");
			item.put("payer_address_tel", "");
			item.put("payer_bank_name_account", "");
			item.put("payee_register_no", "91320000743917098X");
			item.put("payee_register_name", m.get("sellName"));
			item.put("payee_address_tel", m.get("sellAddress"));
			item.put("payee_bank_name_account", m.get("sellBank"));
			item.put("check_code", getTradeNo());
			item.put("out_invoice_id", invoiceId);
			item.put("ori_blue_inv_code", invoiceCode);
			item.put("ori_blue_inv_no", invoiceNo);
			item.put("file_download_type", "PDF");

			//为了防止invoice_id有不同地市重复的情况，传给支付宝的id改为invoiceId+","+invoiceCode+","+invoiceNo，
			//给支付宝的回调接口用这3个参数去查询wx_invoice_order_detail表中的pdfUrl
			String id = invoiceId+","+invoiceCode+","+invoiceNo;
			String strId = UrlUtil.enCryptAndEncode(id);
			item.put("file_download_url", PDFURL + strId);
			item.put("extend_fields", "m_invoice_detail_url");
			logger.info("支付宝侧pdfUrl={},strId={}", PDFURL , strId);

			if (sendInvoice(item)) {
				logger.info("支付宝推送成功invoiceId:{}", invoiceId);
				checkInfoMapper.updateAliStatusSend(invoiceId,invoiceCode,invoiceNo);
				logger.info("支付宝插卡状态更新成功invoiceId:{}", invoiceId);
				RedisUtil.unlock(redisOperation, "电子发票PDF同步", lockKey, lockValue);
			}
		} else {
			logger.info("支付宝未授权invoiceId:{}", invoiceId);
		}
	}

	public static void sendData(Map<String, String> map, String url) {
		String email = map.get("mail");
		String phone = map.get("loginAccNbr");
		String orderId = map.get("orderId");
		String did = map.get("did");
		String didNo = map.get("didNo");
		String titleType = map.get("titleType");
		
		Map<String, String> params = new HashMap<>();
		JSONObject json = new JSONObject();
		JSONObject urlStr = new JSONObject();
		JSONArray array = new JSONArray();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		json.put("toAddress", email); //邮箱
		json.put("accNbr", phone);   //手机号
		json.put("titleType", titleType);   // 抬头类型 1个人 2政企
		json.put("templateId", "78");  //78
		json.put("createDate", df.format(new Date())); //当前日期
		json.put("did", did); //发票唯一Id
		json.put("didNo", didNo);    // 发票唯一id,bigint,短链hash
		json.put("orderId", orderId);//发票订单编号
		urlStr.put("url", url);
		array.add(urlStr);

		json.put("urlStr", array);
		String str = "PathCode=electronicInvoice-0013;loadUrlEmail=" + json.toString();
		logger.info("掌厅加密前入参:{}", str);
		String str1 = RSAUtils.encode(str);
		params.put("para", str1);
		logger.info("掌厅加密后入参:{}", str1);
		String rss = "";
		try {
			// 生产
			long t1 = System.currentTimeMillis();
			rss = HttpClientUtils.doPostMap("http://ztht.telecomjs.com:10000/zt-service/welcome", params);
			long t2 = System.currentTimeMillis();
			insertData(null, phone, null, "00", params.toString(), rss, "8");
			// 测试
			// rss = HttpClientUtils.doPostMap("http://192.168.207.78:8082/zt-service/welcome", params);
			logger.info("掌厅接口回参:{},掌厅接口耗时:{}", rss,t2-t1);
		} catch (Exception e) {
			logger.info("掌厅接口异常：{}", e.getMessage());
			insertData(null, phone, null, "99", params.toString(), rss, "8");
		}
	}

	private static void insertData(String areaCode, String accNbr, String phone, String returnCode, String inputParam, String outParam, String serviceType) {

		ExecutorService executorService = Executors.newSingleThreadExecutor();
		InnerApiLog innerApiLog = new InnerApiLog("dzfp", areaCode, accNbr, phone, serviceType,
				returnCode, inputParam, outParam, "0");
		InnerApiLogThread innerApiLogThread = new InnerApiLogThread(innerApiLog);
		executorService.execute(innerApiLogThread);
		executorService.shutdown();
	}


	private boolean sendInvoice(Map<String, String> map) throws AlipayApiException {

		NacosCommon nacosCommon = SpringUtil.getBean("nacosCommon");
		AlipayClient alipayClient = new DefaultAlipayClient(nacosCommon.getProxyUrl()+URL, InvoiceConstant.APPID, InvoiceConstant.APP_PRIVATE_KEY, FORMAT, CHARSET,
				InvoiceConstant.ALIPAY_PUBLIC_KEY, SIGN_TYPE);

		AlipayEbppInvoiceInfoSendRequest request = new AlipayEbppInvoiceInfoSendRequest();
		StringBuilder stb = new StringBuilder();
		stb.append("{");
		stb.append("\"m_short_name\":\"CHINA_TELECOM\",");
		stb.append("\"sub_m_short_name\":\"JSDX_DQ\",");
		stb.append("      \"invoice_info_list\":[{");
		stb.append(String.format("        \"user_id\":\"%s\",", map.get("user_id")));
		stb.append(String.format("\"invoice_code\":\"%s\",", map.get("invoice_code")));      //发票代码
		stb.append(String.format("\"invoice_no\":\"%s\",", map.get("invoice_no")));          //发票号码
		stb.append(String.format("\"invoice_date\":\"%s\",", map.get("invoice_date")));      //发票日期
		stb.append(String.format("\"sum_amount\":\"%s\",", map.get("sum_amount")));
		stb.append(String.format("\"ex_tax_amount\":\"%s\",", map.get("ex_tax_amount")));
		stb.append(String.format("\"tax_amount\":\"%s\",", map.get("tax_amount")));
		stb.append("          \"invoice_content\":[{");
		stb.append(String.format("            \"item_name\":\"%s\",", map.get("item_name")));
		stb.append(String.format("\"item_no\":\"%s\",", map.get("item_no")));
		stb.append(String.format("\"item_unit\":\"%s\",", map.get("item_unit")));

		stb.append(String.format("\"item_quantity\":%s,", map.get("item_quantity")));
		stb.append(String.format("\"item_unit_price\":\"%s\",", map.get("item_unit_price")));
		stb.append(String.format("\"item_ex_tax_amount\":\"%s\",", map.get("item_ex_tax_amount")));
		stb.append(String.format("\"item_tax_rate\":\"%s\",", map.get("item_tax_rate")));
		stb.append(String.format("\"item_tax_amount\":\"%s\",", map.get("item_tax_amount")));
		stb.append(String.format("\"item_sum_amount\":\"%s\",", map.get("item_sum_amount")));
		stb.append(String.format("\"row_type\":\"%s\"", map.get("row_type")));
		stb.append("            }],");

		stb.append(String.format("\"out_trade_no\":\"%s\",", map.get("out_trade_no"))); //唯一交易流水号时间随机生成
		stb.append(String.format("\"invoice_type\":\"%s\",", map.get("invoice_type")));
		stb.append(String.format("\"invoice_kind\":\"%s\",", map.get("invoice_kind")));
		stb.append("\"invoice_title\":{");
		stb.append(String.format("\"title_name\":\"%s\",", map.get("title_name")));         //购买方名称
		stb.append("\"payer_register_no\":\"\",");
		stb.append("\"payer_address_tel\":\"\",");
		stb.append("\"payer_bank_name_account\":\"\"");
		stb.append("        },");
		stb.append(String.format("\"payee_register_no\":\"%s\",", map.get("payee_register_no")));
		stb.append(String.format("\"payee_register_name\":\"%s\",", map.get("payee_register_name")));
		stb.append(String.format("\"payee_address_tel\":\"%s\",", map.get("payee_address_tel")));
		stb.append(String.format("\"payee_bank_name_account\":\"%s\",", map.get("payee_bank_name_account")));

		stb.append(String.format("\"check_code\":\"%s\",", map.get("check_code")));            //发票校验码
		stb.append(String.format("\"out_invoice_id\":\"%s\",", map.get("out_invoice_id")));    //发票id
		stb.append(String.format("\"ori_blue_inv_code\":\"%s\",", map.get("ori_blue_inv_code")));             //发票代码
		stb.append(String.format("\"ori_blue_inv_no\":\"%s\",", map.get("ori_blue_inv_no")));                 //发票号码 
		stb.append(String.format("\"file_download_type\":\"%s\",", map.get("file_download_type")));
		stb.append(String.format("\"file_download_url\":\"%s\",", map.get("file_download_url")));
		stb.append(String.format("\"extend_fields\":\"%s\"", map.get("extend_fields")));
		stb.append("        }]");
		stb.append("  }");

		logger.info("支付宝入参:{}", stb);
		request.setBizContent(stb.toString());
		AlipayEbppInvoiceInfoSendResponse response = alipayClient.execute(request);
		logger.info("支付宝回参:{}", response.getBody());

		String subCode = response.getSubCode();
		logger.info("支付宝回参sub_code:{}", subCode);

		return (response.isSuccess() || StringUtils.equals(subCode, "RECORD_ALREADY_EXIST")) ;
	}

	private static String getResult(String ts) {
		if (ts.toUpperCase().contains("Z")) {
			try {
				ts = ts.replace("Z", " UTC");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
				Date date = sdf.parse(ts);
//				Calendar c = sdf.getCalendar();
//				return getString(c);
				return DateUtils.formatDate(date,DateUtils.DEFAULT_DATE_FORMAT);
			} catch (ParseException ex) {
				logger.info("ts={}", ts);
				return "";
			}
		}
		return ts;
	}

	private static String getDateResult(String ts) {
		if (ts.toUpperCase().contains("Z")) {
			try {
				ts = ts.replace("Z", " UTC");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
				sdf.parse(ts);
				Calendar c = sdf.getCalendar();
				return getDateString(c);
			} catch (ParseException ex) {
				logger.info("ts={}", ts);
				return "";
			}
		} else {
			return ts.length() > 10 ? ts.substring(0, 10) : "";
		}
	}

	private static String getDateString(Calendar c) {
		StringBuffer result = new StringBuffer();
		result.append(c.get(Calendar.YEAR));
		result.append("-");
		result.append((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1));
		result.append("-");
		result.append((c.get(Calendar.DAY_OF_MONTH)) < 10 ? "0" + (c.get(Calendar.DAY_OF_MONTH)) : (c.get(Calendar.DAY_OF_MONTH)));
		return result.toString().trim();
	}

	private static String getString(Calendar c) {
		StringBuffer result = new StringBuffer();
		result.append(c.get(Calendar.YEAR));
		result.append("-");
		result.append((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1));
		result.append("-");
		result.append((c.get(Calendar.DAY_OF_MONTH)) < 10 ? "0" + (c.get(Calendar.DAY_OF_MONTH)) : (c.get(Calendar.DAY_OF_MONTH)));
		result.append(" ");
		result.append((c.get(Calendar.HOUR_OF_DAY)) < 10 ? "0" + (c.get(Calendar.HOUR_OF_DAY)) : (c.get(Calendar.HOUR_OF_DAY)));
		result.append(":");
		result.append((c.get(Calendar.MINUTE)) < 10 ? "0" + (c.get(Calendar.MINUTE)) : (c.get(Calendar.MINUTE)));
		result.append(":");
		result.append((c.get(Calendar.SECOND)) < 10 ? "0" + (c.get(Calendar.SECOND)) : (c.get(Calendar.SECOND)));
		return result.toString();
	}

	private static String getTradeNo() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String str = sdf.format(date);
		int flag = new Random().nextInt(999999);
		if (flag < 100000) {
			flag += 100000;
		}
		return str + (flag + "");
	}

	private static String changeF2Y(int price) {
		return BigDecimal.valueOf(price).divide(new BigDecimal(100)).toString();
	}
}
